package com.socool.sinofaith.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import com.deying.actionbarcompat.ActionBarHelperBase;
import com.deying.actionbarcompat.ActionBarHelperBase.CenterViewFactory;
import com.deying.actionbarcompat.ActionBarHelperBase.SpinnerViewFactory;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.adapter.SubTaskAdapter;
import com.socool.sinofaith.dao.QuestionAnswerDao;
import com.socool.sinofaith.dao.SifQuestionOptionsDao;
import com.socool.sinofaith.dao.SifSubTaskDao;
import com.socool.sinofaith.dao.SifTaskDao;
import com.socool.sinofaith.dao.SifTaskQuestionDao;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.AnswerReq;
import com.socool.sinofaith.model.BaseMessage;
import com.socool.sinofaith.model.QuestionAnswerBean;
import com.socool.sinofaith.model.QuestionAnswerReqBean;
import com.socool.sinofaith.model.SifQuestionOptionsBean;
import com.socool.sinofaith.model.SifSubTaskBean;
import com.socool.sinofaith.model.SifTaskBean;
import com.socool.sinofaith.model.SifTaskQuestionBean;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.S;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;
import com.socool.sinofaith.view.MyDialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

/**
 * 点击开始任务后进入
 * @author jiang
 *
 */
public class SubTaskActivity extends BaseActivity
		implements CenterViewFactory, SpinnerViewFactory, View.OnClickListener {

	ActionBarHelperBase mActionBarHelperBase;
	private PullToRefreshListView mPullToRefreshListView;
	private SubTaskAdapter mSubTaskAdapter;
	private String taskid, Task_Name;
	private SifTaskBean taskBean;
	private LoadingDialog mLoadingDialog;
	private String userMobile;
	private int count, totalcount, failcount, failtotalcount = 0;
	private List<AjaxParams> paramsList = new ArrayList<AjaxParams>();
	private String end = "0";

	Dialog dialog;
	Lock lock = new ReentrantLock();

	int fcount = 0;

	HashMap<String, String> firstParamsMap = new HashMap<String, String>();

	int success;
	int sum;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_task);
		SocoolApplication.addActivity(this);

		mLoadingDialog = new LoadingDialog(this);
		mActionBarHelperBase = (ActionBarHelperBase) this.getActionBarHelper();
		mActionBarHelperBase.setmCenterViewFactory(this);
		mActionBarHelperBase.setmSpinnerViewFactory(this);
		mActionBarHelperBase.setmClickListener(this);
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.subListview);
		mSubTaskAdapter = new SubTaskAdapter(this, mPullToRefreshListView.getRefreshableView());
		mPullToRefreshListView.getRefreshableView().setAdapter(mSubTaskAdapter);
		taskid = this.getIntent().getStringExtra("taskid");
		userMobile = getSPString();
		mPullToRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				String countString = mSubTaskAdapter.getMdatas().get(arg2 - 1).getHasChild();
				int count = 0;
				if (!TextUtils.isEmpty(countString)) {
					try {
						count = Integer.parseInt(countString);
					} catch (NumberFormatException e) {

					}
				}
				if (count > 0) {
					Intent intent = new Intent(SubTaskActivity.this, ChildTaskActivity.class);
					intent.putExtra("subtaskid", mSubTaskAdapter.getMdatas().get(arg2 - 1).getSubTask_ID());
					intent.putExtra("taskid", taskid);
					SubTaskActivity.this.startActivity(intent);

				} else {
					Intent intent = new Intent(SubTaskActivity.this, AnswerQuestionActivity.class);
					intent.putExtra("type", "1");
					intent.putExtra("flag", "0");
					intent.putExtra("Template_ID", mSubTaskAdapter.getMdatas().get(arg2 - 1).getTemplate_ID());
					intent.putExtra("taskid", taskid);
					intent.putExtra("subtaskid", mSubTaskAdapter.getMdatas().get(arg2 - 1).getSubTask_ID());
					SubTaskActivity.this.startActivity(intent);
				}

			}
		});

		SifTaskDao taskDao = new SifTaskDao(this);
		List<SifTaskBean> tasklist = taskDao
				.queryBySql("select * from " + SifTaskBean.TABLENAME + " where Task_ID=" + taskid);
		Task_Name = "任务";
		if (null != tasklist && tasklist.size() > 0) {
			taskBean = tasklist.get(0);
			Task_Name = taskBean.getTaskName();
		}
	}

	void getData() {
		new AsyncTask<Void, Void, ArrayList<SifSubTaskBean>>() {

			@Override
			protected ArrayList<SifSubTaskBean> doInBackground(Void... arg0) {
				SifSubTaskDao subTaskDao = new SifSubTaskDao(SubTaskActivity.this);
				return subTaskDao.queryBySql("select * from " + SifSubTaskBean.TABLENAME + " where Task_ID=" + taskid);
			}

			@Override
			protected void onPostExecute(ArrayList<SifSubTaskBean> result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (result != null) {
					mSubTaskAdapter.setMdatas(result);
					mSubTaskAdapter.notifyDataSetChanged();
				}
			}
		}.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.common, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public View createView() {

		TextView tv = new TextView(this);
		tv.setText(Task_Name);
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(20);
		return tv;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { // TODO Auto-generated
															// method stub
		if (item.getItemId() == R.id.home) {
			finish();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private static final int id = 1000000;

	@Override
	public View createSpinnerView() {
		// ImageView imageview = new ImageView(this);
		// return imageview;
		TextView tv = new TextView(this);
		tv.setText("提交统计");
		tv.setTextColor(this.getResources().getColor(R.color.white));
		tv.setTextSize(14);
		tv.setPadding(0, 0, 20, 0);
		tv.setId(id);
		return tv;
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case id:
			Intent intent = new Intent(SubTaskActivity.this, SyncTaskActivity.class);
			intent.putExtra(SyncTaskActivity.TASK_ID, taskid);
			intent.putExtra(SyncTaskActivity.TASK_NAME, Task_Name);
			startActivity(intent);
		}
	}

	public void autoAnswer(String Template_ID, String subtaskid) {
		SifTaskQuestionDao questionDao = new SifTaskQuestionDao(this);
		ArrayList<SifTaskQuestionBean> questionBeans = questionDao.queryBySql(
				"select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='" + Template_ID + "'");
		SifQuestionOptionsDao questionOptionsDao = new SifQuestionOptionsDao(this);

		ArrayList<AnswerReq> SubAnswer = new ArrayList<AnswerReq>();
		if (null != questionBeans && questionBeans.size() > 0) {
			for (int i = 0; i < questionBeans.size(); i++) {
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(i);
				ArrayList<SifQuestionOptionsBean> optionsBeans = questionOptionsDao
						.queryBySql("select * from " + SifQuestionOptionsBean.TABLENAME + " where TaskQuestion_ID='"
								+ taskQuestionBean.getTaskQuestion_ID() + "'");
				String answer = "";

				if (null != optionsBeans && optionsBeans.size() > 0) {
					for (int k = 0; k < optionsBeans.size(); k++) {
						SifQuestionOptionsBean questionOptionsBean = optionsBeans.get(k);
						if (questionOptionsBean.getIsDefault().equals("1")) {
							answer = questionOptionsBean.getOptionValue();
						}
					}
				}
				// 缓存
				QuestionAnswerBean answerBean = new QuestionAnswerBean();
				if ("1".equals(taskQuestionBean.getQuestionType()) || "2".equals(taskQuestionBean.getQuestionType())) {

					AnswerReq answerReq = new AnswerReq();
					answerBean.setTask_ID(taskid);
					answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
					answerBean.setSubTask_ID(subtaskid);
					answerBean.setSubmiter(userMobile);
					answerBean.setFileCount("");
					answerReq.setFileCount("");
					// 单选题有其他选项
					answerBean.setAnswer(answer);
					answerReq.setAnswer(answer);
					answerBean.setAnswerType("1");
					answerBean.setIsFinish("0");
					answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());

					SubAnswer.add(answerReq);

					// 检测本地是否已答,并执行增加/更新操作
					QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
					List<QuestionAnswerBean> answerlist = answerDao.queryBySql("select * from "
							+ QuestionAnswerBean.TABLENAME + " where Task_ID='" + answerBean.getTask_ID()
							+ "' and SubTask_ID='" + answerBean.getSubTask_ID() + "' and TaskQuestion_ID='"
							+ taskQuestionBean.getTaskQuestion_ID() + "' and Submiter='" + userMobile + "'");
					// Log.v("qqqq",
					// answerlist.get(0).getTask_ID()+"==="+answerlist.get(0).getTaskQuestion_ID()+"==="+answerlist.get(0).getAnswer());
					if (null != answerlist && answerlist.size() > 0) {
						QuestionAnswerBean oldanswerBean = answerlist.get(0);
						answerBean.setID(oldanswerBean.getID());
						answerDao.update(answerBean);
					} else {
						answerDao.insert(answerBean);
					}

				} else {
					if (taskQuestionBean.getIsRequired().equals("0")) {
						AnswerReq answerReq = new AnswerReq();
						answerBean.setTask_ID(taskid);
						answerBean.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());
						answerBean.setSubTask_ID(subtaskid);
						answerBean.setSubmiter(userMobile);
						answerBean.setFileCount("");
						answerReq.setFileCount("");
						// 单选题有其他选项
						answerBean.setAnswer("");
						answerReq.setAnswer("");
						answerBean.setAnswerType("1");
						answerBean.setIsFinish("0");
						answerReq.setTaskQuestion_ID(taskQuestionBean.getTaskQuestion_ID());

						SubAnswer.add(answerReq);

						// 检测本地是否已答,并执行增加/更新操作
						QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
						List<QuestionAnswerBean> answerlist = answerDao.queryBySql("select * from "
								+ QuestionAnswerBean.TABLENAME + " where Task_ID='" + answerBean.getTask_ID()
								+ "' and SubTask_ID='" + answerBean.getSubTask_ID() + "' and TaskQuestion_ID='"
								+ taskQuestionBean.getTaskQuestion_ID() + "' and Submiter='" + userMobile + "'");
						// Log.v("qqqq",
						// answerlist.get(0).getTask_ID()+"==="+answerlist.get(0).getTaskQuestion_ID()+"==="+answerlist.get(0).getAnswer());
						if (null != answerlist && answerlist.size() > 0) {
							QuestionAnswerBean oldanswerBean = answerlist.get(0);
							answerBean.setID(oldanswerBean.getID());
							answerDao.update(answerBean);
						} else {
							answerDao.insert(answerBean);
						}
					}
				}

				// 当前题目为最后一题时
				if (taskQuestionBean.getOrderIndex().equals(questionBeans.size() + "")) {
					QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
					ArrayList<QuestionAnswerBean> answerlist = answerDao
							.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='"
									+ answerBean.getTask_ID() + "' and SubTask_ID='" + answerBean.getSubTask_ID()
									+ "' and Submiter='" + userMobile + "'");
					if (null != answerlist && answerlist.size() > 0) {
						for (int j = 0; j < answerlist.size(); j++) {
							answerBean = answerlist.get(j);
							answerBean.setIsFinish("1");
							answerDao.update(answerBean);
						}
					} else {
						Toast.makeText(SubTaskActivity.this, "该问卷不支持自动答题，请手动答题", Toast.LENGTH_LONG).show();
					}
				}
			}
		}
		// 清空数据重新请求
		mSubTaskAdapter.getMdatas().clear();
		getData();
		mLoadingDialog.dismiss();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public QuestionAnswerReqBean submitAnswer(String Template_ID, final String subtaskid) {
		success = 0;
		sum = 0;

		final QuestionAnswerReqBean answerReqBean = new QuestionAnswerReqBean();
		answerReqBean.setTask_ID(taskid);
		answerReqBean.setSubTask_ID(subtaskid);
		answerReqBean.setStemp_ID("");
		answerReqBean.setSubmiter(userMobile);
		ArrayList<AnswerReq> SubAnswer = new ArrayList<AnswerReq>();
		QuestionAnswerDao answerDao = new QuestionAnswerDao(this);
		ArrayList<QuestionAnswerBean> answerlist = answerDao
				.queryBySql("select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID='" + taskid
						+ "' and SubTask_ID='" + subtaskid + "' and Submiter='" + userMobile + "'");
		SifTaskQuestionDao questionDao = new SifTaskQuestionDao(this);

		if (null != answerlist && answerlist.size() > 0) {
			for (int i = 0; i < answerlist.size(); i++) {
				QuestionAnswerBean answerBean = answerlist.get(i);
				AnswerReq answerReq = new AnswerReq();
				answerReq.setAnswer(answerBean.getAnswer());
				answerReq.setFileCount(answerBean.getFileCount());
				answerReq.setOtherAnswer(answerBean.getOtherAnswer());
				answerReq.setTaskQuestion_ID(answerBean.getTaskQuestion_ID());

				ArrayList<SifTaskQuestionBean> questionBeans = questionDao
						.queryBySql("select * from " + SifTaskQuestionBean.TABLENAME + " where Template_ID='"
								+ Template_ID + "' and TaskQuestion_ID=" + answerBean.getTaskQuestion_ID());
				SifTaskQuestionBean taskQuestionBean = questionBeans.get(0);
				answerReq.setQuestion(taskQuestionBean.getQuestion());
				answerReq.setQuestionType(taskQuestionBean.getQuestionType());
				answerReq.setOrder(taskQuestionBean.getOrderIndex());
				answerReq.setGPS(answerBean.getGPS());
				SubAnswer.add(answerReq);
			}
		}
		answerReqBean.setSubAnswer(SubAnswer);
		String tempjson = "";
		try {
			if (null != answerReqBean.getSubAnswer() && answerReqBean.getSubAnswer().size() > 0) {
				for (int i = 0; i < answerReqBean.getSubAnswer().size(); i++) {
					AnswerReq answerReq = answerReqBean.getSubAnswer().get(i);
					if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
							&& !"0".equals(answerReq.getFileCount())) {
						for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
							count++;
							totalcount++;

							sum++;
						}
					}
				}
			}

			tempjson = HttpJsonAdapter.getInstance().toJson(answerReqBean);
			// Toast.makeText(this, tempjson, Toast.LENGTH_LONG).show();
			Log.v("qqqq", tempjson);
		} catch (Exception e) {
			e.printStackTrace();
		}
		end = "0";
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadAnswer_url);
		params.put("did", SinofaithUtil.did);
		params.put("dajson", tempjson);
		if (totalcount == 0) {
			params.put("taskfinally", "1");
		}
		fh.post(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {

			@Override
			public void onStart() {
				if (!mLoadingDialog.isShowing()) {
					mLoadingDialog.show();
				}
				super.onStart();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				mLoadingDialog.dismiss();
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {
						// QuestionAnswerDao answerDao = new QuestionAnswerDao(
						// ChildTaskActivity.this);
						// if (null != answerlist && answerlist.size() > 0) {
						// for (int i = 0; i < answerlist.size(); i++) {
						// QuestionAnswerBean answerBean = answerlist
						// .get(i);
						// answerBean.setIsFinish("2");
						// answerDao.update(answerBean);
						// }
						// }
						// Toast.makeText(ChildTaskActivity.this,
						// baseMessage.getDesc(), Toast.LENGTH_LONG)
						// .show();
						if (count == 0) {
							QuestionAnswerDao answerDao = new QuestionAnswerDao(SubTaskActivity.this);
							// List<QuestionAnswerBean> answerlist = answerDao
							// .queryBySql("select * from "
							// + QuestionAnswerBean.TABLENAME
							// + " where Task_ID='" + answerBean.getTask_ID()
							// + "' and SubTask_ID='"
							// +
							// answerBean.getSubTask_ID()+"' and
							// Stemp_ID='"+answerBean.getStemp_ID()+"' and
							// Submiter='"+userMobile+"'");

							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + subtaskid;
							sql += " and Submiter=" + userMobile;
							List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
							if (null != answerlist && answerlist.size() > 0) {
								for (int i = 0; i < answerlist.size(); i++) {
									QuestionAnswerBean answerBean = answerlist.get(i);
									answerBean.setIsFinish("2");
									answerDao.update(answerBean);
								}
							}
							Toast.makeText(SubTaskActivity.this, "提交成功，谢谢参与！", Toast.LENGTH_LONG).show();
							// 清空数据重新请求
							mSubTaskAdapter.getMdatas().clear();
							getData();
						} else {
							ArrayList<AnswerReq> answerReqs = answerReqBean.getSubAnswer();
							if (null != answerReqs && answerReqs.size() > 0) {
								int begin = 0;
								for (int i = 0; i < answerReqs.size(); i++) {
									AnswerReq answerReq = answerReqs.get(i);
									if (null != answerReq.getFileCount() && !"".equals(answerReq.getFileCount())
											&& !"0".equals(answerReq.getFileCount())) {
										String[] temps = answerReq.getAnswer().split("#");
										for (int j = 0; j < Integer.valueOf(answerReq.getFileCount()); j++) {
											Log.v("qqqq", temps[j]);
											if (null != temps[j] && !"".equals(temps[j])) {
												File file = new File(temps[j]);
												final String temppath = temps[j];
												String fileName = file.getName();
												String fileType = fileName.substring(fileName.lastIndexOf(".") + 1,
														fileName.length());
												if (j == (Integer.valueOf(answerReq.getFileCount()) - 1)) {
													end = "1";
												}
												String qtype = "1";
												if ("3".equals(answerReq.getQuestionType())) {
													qtype = "1";
												} else if ("4".equals(answerReq.getQuestionType())) {
													qtype = "2";
												} else {
													qtype = "3";
												}
												if (begin == 0 && count > 1) {
													firstParamsMap.put("taskid", answerReqBean.getTask_ID());
													firstParamsMap.put("subtaskid", answerReqBean.getSubTask_ID());
													firstParamsMap.put("tempid", answerReqBean.getStemp_ID());
													firstParamsMap.put("questionid", answerReq.getTaskQuestion_ID());
													firstParamsMap.put("mobile", userMobile);
													firstParamsMap.put("ftype", qtype);
													firstParamsMap.put("suffix", fileType);
													firstParamsMap.put("order", answerReq.getOrder());
													firstParamsMap.put("desc", answerReq.getOtherAnswer());
													firstParamsMap.put("path", temppath);
													firstParamsMap.put("GPS", answerReq.getGPS());
													totalcount--;
													begin++;
													continue;
												}
												mLoadingDialog.show();
												uploadFile(answerReqBean.getTask_ID(), answerReqBean.getSubTask_ID(),
														answerReqBean.getStemp_ID(), answerReq.getTaskQuestion_ID(),
														qtype, fileType, answerReq.getOrder(),
														answerReq.getOtherAnswer(), file, answerReq.getGPS());
											}
										}
									}
								}
							}
						}

					} else {
						Toast.makeText(SubTaskActivity.this, baseMessage.getDesc(), Toast.LENGTH_LONG).show();

					}
				} catch (Exception e) {
					Toast.makeText(SubTaskActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				mLoadingDialog.dismiss();
				super.onFailure(t, errorNo, strMsg);
				Toast.makeText(SubTaskActivity.this, strMsg, Toast.LENGTH_LONG).show();
			}

		});
		return answerReqBean;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void uploadFile(final String taskid, final String subtaskid, final String tempid, final String questionid,
			String ftype, String suffix, String order, String desc, File file, String GPS) {
		if (totalcount > 0) {
			totalcount--;
		}
		FinalHttp fh = new FinalHttp();
		final AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.uploadFile_url);
		params.put("did", SinofaithUtil.did);
		params.put("taskid", taskid);
		params.put("subtaskid", subtaskid);
		params.put("tempid", tempid);
		params.put("questionid", questionid);
		params.put("mobile", userMobile);
		params.put("ftype", ftype);
		params.put("suffix", suffix);
		params.put("order", order);
		params.put("desc", desc);
		params.put("finally", end);
		if (count == 1) {
			params.put("taskfinally", "1");
		}
		params.put("GPS", GPS);
		try {
			S.FileParams(this, params, file);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		Log.v("qqqq", ConstansJsonUrl.REQUEST_URL + "?" + params);
		end = "0";
		fh.post(ConstansJsonUrl.REQUEST_URL, null, params, null, new AjaxCallBack() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				// if(!mLoadingDialog.isShowing()){
				// mLoadingDialog.show();
				// }
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				super.onSuccess(t);
				try {
					BaseMessage baseMessage = HttpJsonAdapter.getInstance().get(t.toString(), BaseMessage.class);
					if (baseMessage.getResult().equals("0")) {
						// if (count > 0) {
						count--;
						success++;
						// }
						if (count == 1) {
							File file = new File(firstParamsMap.get("path"));
							if (null != file && file.exists()) {
								mLoadingDialog.show();
								end = "1";
								uploadFile(firstParamsMap.get("taskid"), firstParamsMap.get("subtaskid"),
										firstParamsMap.get("tempid"), firstParamsMap.get("questionid"),
										firstParamsMap.get("ftype"), firstParamsMap.get("suffix"),
										firstParamsMap.get("order"), firstParamsMap.get("desc"), file,
										firstParamsMap.get("GPS"));
							}
						}
						if (count == 0) {
							mLoadingDialog.dismiss();
							QuestionAnswerDao answerDao = new QuestionAnswerDao(SubTaskActivity.this);
							String sql = "select * from " + QuestionAnswerBean.TABLENAME + " where Task_ID=" + taskid
									+ " and SubTask_ID=" + subtaskid;
							if (null != tempid && !"".equals(tempid)) {
								sql += " and Stemp_ID=" + tempid;
							}
							sql += " and Submiter=" + userMobile;
							List<QuestionAnswerBean> answerlist = answerDao.queryBySql(sql);
							if (null != answerlist && answerlist.size() > 0) {
								for (int i = 0; i < answerlist.size(); i++) {
									QuestionAnswerBean answerBean = answerlist.get(i);
									answerBean.setIsFinish("2");
									answerDao.update(answerBean);
								}
							}

							// Toast.makeText(SubTaskActivity.this,
							// "提交成功，谢谢参与！", Toast.LENGTH_LONG).show();
							ChildTaskActivity.showDialog(SubTaskActivity.this, sum, success);
							mSubTaskAdapter.getMdatas().clear();
							getData();
						}

					} else {
						mLoadingDialog.dismiss();
						Log.v("error", baseMessage.getDesc());
						// Toast.makeText(SubTaskActivity.this,
						// baseMessage.getDesc(),
						// Toast.LENGTH_LONG).show();
						paramsList.add(params);
						reUpload(subtaskid);
					}
				} catch (Exception e) {
					mLoadingDialog.dismiss();
					Log.v("error", e.getMessage());
					// Toast.makeText(SubTaskActivity.this,
					// e.getMessage(), Toast.LENGTH_LONG)
					// .show();
					paramsList.add(params);
					reUpload(subtaskid);
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				mLoadingDialog.dismiss();
				super.onFailure(t, errorNo, strMsg);
				// Toast.makeText(SubTaskActivity.this, strMsg,
				// Toast.LENGTH_LONG).show();
				paramsList.add(params);
				reUpload(subtaskid);
			}

		});
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	void reUpload(final String subtaskid) {
		mLoadingDialog.dismiss();
		fcount++;
		if (null != paramsList && paramsList.size() > 0) {
			if (null != dialog && dialog.isShowing()) {
				return;
			}
			MyDialog.Builder builder = new MyDialog.Builder(this);
			builder.setTitle("当前网络异常，请稍候尝试提交").setPositiveButton("确定",
					new android.content.DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog111, int which) {
							// dialog.dismiss();
							// mLoadingDialog.show();
							// failcount=paramsList.size();
							// failtotalcount=paramsList.size();
							// for(int i=0;i<paramsList.size();i++){
							// final AjaxParams params=paramsList.get(i);
							// if(null!=params){
							// if(failtotalcount>0){
							// failtotalcount--;
							// }
							// FinalHttp fh = new FinalHttp();
							// fh.post(ConstansJsonUrl.REQUEST_URL,null,
							// params,null, new AjaxCallBack() {
							// @Override
							// public void onStart() {
							// // TODO Auto-generated method stub
							// super.onStart();
							// // if(!mLoadingDialog.isShowing()){
							// mLoadingDialog.show();
							// // }
							// }
							//
							// @Override
							// public void onLoading(long count, long current) {
							// // TODO Auto-generated method stub
							// super.onLoading(count, current);
							// }
							//
							// @Override
							// public void onSuccess(Object t) {
							// super.onSuccess(t);
							// try {
							// BaseMessage baseMessage = HttpJsonAdapter
							// .getInstance().get(t.toString(),
							// BaseMessage.class);
							// if (baseMessage.getResult().equals("0")) {
							// if(failcount>0){
							// failcount--;
							// }
							// if(failcount==0){
							// mLoadingDialog.dismiss();
							// QuestionAnswerDao answerDao = new
							// QuestionAnswerDao(
							// SubTaskActivity.this);
							// String sql = "select * from "
							// + QuestionAnswerBean.TABLENAME +
							// " where Task_ID="
							// + taskid + " and SubTask_ID=" + subtaskid;
							// sql += " and Submiter="
							// + SinofaithUtil.userInfo.getUserMobile();
							// List<QuestionAnswerBean> answerlist = answerDao
							// .queryBySql(sql);
							// if(null!=answerlist && answerlist.size()>0){
							// for(int i=0;i<answerlist.size();i++){
							// QuestionAnswerBean answerBean=answerlist.get(i);
							// answerBean.setIsFinish("2");
							// answerDao.update(answerBean);
							// }
							// }
							// Toast.makeText(SubTaskActivity.this,
							// "提交成功，谢谢参与！", Toast.LENGTH_LONG).show();
							// mSubTaskAdapter.getMdatas().clear();
							// getData();
							// }
							// lock.unlock();
							// } else {
							// mLoadingDialog.dismiss();
							// Log.v("error", baseMessage.getDesc());
							// // Toast.makeText(SubTaskActivity.this,
							// // baseMessage.getDesc(),
							// // Toast.LENGTH_LONG).show();
							// paramsList.add(params);
							// // if(totalcount==0){
							// reUpload(subtaskid);
							// // }
							// }
							// } catch (Exception e) {
							// mLoadingDialog.dismiss();
							// Log.v("error", e.getMessage());
							// // Toast.makeText(SubTaskActivity.this,
							// // e.getMessage(), Toast.LENGTH_LONG)
							// // .show();
							// paramsList.add(params);
							// // if(totalcount==0){
							// reUpload(subtaskid);
							// // }
							// }
							//
							// }
							//
							// @Override
							// public void onFailure(Throwable t, int errorNo,
							// String strMsg) {
							// mLoadingDialog.dismiss();
							// super.onFailure(t, errorNo, strMsg);
							// // Toast.makeText(SubTaskActivity.this, strMsg,
							// // Toast.LENGTH_LONG).show();
							// paramsList.add(params);
							// // if(totalcount==0){
							// reUpload(subtaskid);
							// // }
							// }
							//
							// });
							// dialog.dismiss();
							// }
							// }
							if (fcount >= 1) {
								Toast.makeText(SubTaskActivity.this, "当前网络异常，请稍候尝试提交", Toast.LENGTH_LONG).show();
								dialog.dismiss();
								dialog = null;
								ChildTaskActivity.showDialog(SubTaskActivity.this, sum, success);
							}
						}
					});
			// .setNegativeButton(
			// "取消",
			// new android.content.DialogInterface.OnClickListener() {
			//
			// @Override
			// public void onClick(
			// DialogInterface dialog,
			// int which) {
			// mLoadingDialog.dismiss();
			// dialog.dismiss();
			// dialog=null;
			// paramsList.clear();
			// lock.unlock();
			// // 清空数据重新请求
			// mSubTaskAdapter.getMdatas().clear();
			// getData();
			// }
			// });
			dialog = builder.create();
			if (!dialog.isShowing()) {
				dialog.show();
			}
		}
	}

	@Override
	protected void onResume() {
		mSubTaskAdapter.getMdatas().clear();
		getData();
		super.onResume();
	}

	private String getSPString() {
		SharedPreferences sp = this.getSharedPreferences("login", Context.MODE_PRIVATE);
		return sp.getString("UserMobile", "");
	}

}
